package com.cyl.manager.yee.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.cyl.manager.yee.convert.YeeMerchantConvert;
import com.cyl.manager.yee.domain.YeeMerchant;
import com.cyl.manager.yee.pojo.query.YeeMerchantAdd;
import com.cyl.manager.yee.pojo.query.YeeMerchantQuery;
import com.cyl.manager.yee.service.YeeMerchantService;
import com.cyl.yeepay.dto.BalanceDto;
import com.cyl.yeepay.setvice.YeePayMerService;
import com.cyl.yeepay.setvice.YeePayService;
import com.cyl.manager.yee.pojo.vo.YeeMerchantVO;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.yeepay.yop.sdk.service.account.model.BalanceQueryAccountInfoRespDTOResult;
import com.yeepay.yop.sdk.service.mer.model.RegisterQueryV2NetInProgressQueryRespDtoResult;
import com.yeepay.yop.sdk.service.settle.model.SelfSettleQueryResponseDto;
import com.yeepay.yop.sdk.service.std.model.YopQueryBalanceResponseDTO;
import com.yeepay.yop.sdk.service.sys.model.MerchantQualUploadMerFileUploadRespDtoResult;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
/**
 * 商户管理Controller
 *
 * @author zcc
 * @date 2025-03-10
 */
@Api(description ="商户管理接口列表")
@RestController
@RequestMapping("/yee/yeeMerchant")
public class YeeMerchantController extends BaseController {
    @Autowired
    private YeeMerchantService service;
    @Autowired
    private YeeMerchantConvert convert;
    @Autowired
    private YeePayService yeePayService;
    
    @Autowired
    private  YeePayMerService yeePayMerService;
    @ApiOperation("查询商户管理列表")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:list')")
    @PostMapping("/list")
    public ResponseEntity<Page<YeeMerchant>> list(@RequestBody YeeMerchantQuery query, Pageable page) {
    	Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
        if(qrDeptZbjId!=null) {
        	query.setDeptZbjId(qrDeptZbjId);
        }
        List<YeeMerchant> list = service.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }

    @ApiOperation("导出商户管理列表")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:export')")
    @Log(title = "商户管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public ResponseEntity<String> export(YeeMerchantQuery query) {
    	Long qrDeptZbjId = SecurityUtils.getDeptZbjId();
        if(qrDeptZbjId!=null) {
        	query.setDeptZbjId(qrDeptZbjId);
        }
        List<YeeMerchant> list = service.selectList(query, null);
        ExcelUtil<YeeMerchantVO> util = new ExcelUtil<>(YeeMerchantVO.class);
        return ResponseEntity.ok(util.writeExcel(convert.dos2vos(list), "商户管理数据"));
    }

    @ApiOperation("获取商户管理详细信息")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:query')")
    @GetMapping(value = "/{id}")
    public ResponseEntity<YeeMerchant> getInfo(@PathVariable("id") Long id) {
        return ResponseEntity.ok(service.selectById(id));
    }

    
    @ApiOperation("查询商户管理详细信息更新进度")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:query')")
    @GetMapping(value = "registerQuery/{id}")
    public ResponseEntity<YeeMerchant> registerQuery(@PathVariable("id") Long id) {
        return ResponseEntity.ok(service.registerQueryV2(id));
    }
    
    
    
    /**
     * 查询余额查询
     * @param date
     * @param merchantNo
     * @return
     */
    @ApiOperation("查询系统余额查询")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:query')")
    @GetMapping(value = "/getSysMerchantrAmount")
    public  ResponseEntity<YopQueryBalanceResponseDTO> getSysMerchantrAmount(String date) {
        return ResponseEntity.ok(service.getSysMerchantrAmount(date));
    }
    
    /**
     * 查询余额查询
     * @param date
     * @param merchantNo
     * @return
     */
    @ApiOperation("查询系统余额查询")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:query')")
    @GetMapping(value = "/getMerchantrAmount")
    public  ResponseEntity<YopQueryBalanceResponseDTO> getMerchantrAmount(String date,String merchantNo) {
        return ResponseEntity.ok(service.getMerchantrAmount(date, merchantNo));
    }
    
    
    @ApiOperation("查询-日终余额和待结算金额查询余额-商户可结算金额-未结算金额")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:query')")
    @GetMapping(value = "/endBalanceAddBalanceQuery")
    public  ResponseEntity<BalanceDto> endBalanceAddBalanceQuery(String date,String merchantNo) {
        return ResponseEntity.ok(yeePayService.endBalanceAddBalanceQuery(date, merchantNo));
    }
    
    @ApiOperation("日终余额查询")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:query')")
    @GetMapping(value = "/endBalanceQuery")
    public  ResponseEntity<YopQueryBalanceResponseDTO> endBalanceQuery(String date,String merchantNo) {
        return ResponseEntity.ok(yeePayService.endBalanceQuery(date, merchantNo));
    }
 
    @ApiOperation("资金账户余额查询")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:query')")
    @GetMapping(value = "/balanceQueryByZj")
    public  ResponseEntity<BalanceQueryAccountInfoRespDTOResult> balanceQueryByZj() {
        return ResponseEntity.ok(yeePayService.balanceQueryByZj()); 
    }
    
    @ApiOperation("待结算金额查询")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:query')")
    @GetMapping(value = "/balanceQuery")
    public  ResponseEntity<SelfSettleQueryResponseDto> balanceQuery(String date,String merchantNo) {
        return ResponseEntity.ok(yeePayService.balanceQuery(date, merchantNo));
    }
    
    
 
 
    
    
    @ApiOperation("添加已注册商户")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:add')")
    @Log(title = "添加已注册商户", businessType = BusinessType.INSERT)
    @PostMapping
    public ResponseEntity<Integer> add(@RequestBody YeeMerchant yeeMerchant) {
        return ResponseEntity.ok(service.insert(yeeMerchant));
    }
    
    @ApiOperation("修改已注册商户")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:edit')")
    @Log(title = "修改已注册商户", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseEntity<Integer> update(@RequestBody YeeMerchant yeeMerchant) {
        return ResponseEntity.ok(service.update(yeeMerchant));
    }
    
    

    @ApiOperation("修改商户提现卡")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:edit')")
    @Log(title = "修改商户提现卡", businessType = BusinessType.UPDATE)
    @PutMapping("/updateBankCard")
    public ResponseEntity<Integer> updateBankCard(@RequestBody YeeMerchant yeeMerchant) {
        return ResponseEntity.ok(service.updateBankCard(yeeMerchant));
    }

    @ApiOperation("修改基本信息 名称和分类")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:edit')")
    @Log(title = "修改基本信息名称和分类", businessType = BusinessType.UPDATE)
    @PutMapping("/updateYeeMerchantJbxx")
    public ResponseEntity<Integer> updateYeeMerchantJbxx(@RequestBody YeeMerchant yeeMerchant) {
        return ResponseEntity.ok(service.updateYeeMerchantJbxx(yeeMerchant));
    }
 
    
   
    
    public  File convertToFile(MultipartFile multipartFile) {
    	try {
    		 // 创建一个临时文件
            File convFile = Files.createTempFile(multipartFile.getOriginalFilename(), "").toFile();
            // 将MultipartFile的内容写入到这个临时文件
            multipartFile.transferTo(convFile);
            return convFile;
		} catch (Exception e) {
         	throw new RuntimeException("操作失败！msg:"+e.getMessage());
		}
       
    }
    @ApiOperation("网资质文件上传")
    @PostMapping("merchantQualUpload") // /yee/yeeMerchant
    public AjaxResult uploadFile(MultipartFile file) {
    	MerchantQualUploadMerFileUploadRespDtoResult result = yeePayMerService.merchantQualUpload(convertToFile(file));
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", file.getOriginalFilename());
        ajax.put("url", result.getMerQualUrl());
        return ajax;
    }
    
// Map<String, Object> params = yeeMerchant.getParams();
//	"legalLicenceFrontUrl":"法人证件人像面照片地址", 
//	"legalLicenceBackUrl":"法人证件非人像面照片地址",
//	"province":"经营省", 
//	"city":"经营市", 
//	 "district":"经营区", 
//   "address":"经营地址"
    @ApiOperation("新增小微商户saas方式")
    @PreAuthorize("@ss.hasPermi('yee:yeeMerchant:addsaas')")
    @Log(title = "新增小微商户saas方式", businessType = BusinessType.INSERT)
    @PostMapping("/addXwShBySaas") // /yee/yeeMerchant
    public ResponseEntity<YeeMerchant> addXwShBySaas(@RequestBody YeeMerchant yeeMerchant) {
        return ResponseEntity.ok(service.registerSaasMicroV2(yeeMerchant));
    }
     
}
